<?php
class ModelAdmininfoUser extends Model {
	public function addUser($data) {
		$this->db->query("INSERT INTO `" . DB_PREFIX . "user` SET username = '" . $this->db->escape($data['username']) 
		. "', password = '" . $this->db->escape(md5($data['password'])) 
		. "', firstname = '" . $this->db->escape($data['firstname']) 
		. "', lastname = '" . $this->db->escape($data['lastname']) 
		. "', email = '" . $this->db->escape($data['email']) 
		. "', user_group_id = '" . (int)$data['user_group_id'] 
		. "', status = '" . (int)$data['status'] 
		. "', date_added = NOW()");
	}
	
	public function editUser($user_id, $data) {
		$this->db->query("UPDATE `" . DB_PREFIX . "user` SET username = '" . $this->db->escape($data['username']) 
		. "', firstname = '" . $this->db->escape($data['firstname']) 
		. "', lastname = '" . $this->db->escape($data['lastname']) 
		. "', email = '" . $this->db->escape($data['email']) 
		. "', user_group_id = '" . (int)$data['user_group_id'] 
		. "', status = '" . (int)$data['status'] 
		. "' WHERE user_id = '" . (int)$user_id . "'");
		
		if ($data['password']) {
			$this->db->query("UPDATE `" . DB_PREFIX . "user` SET password = '" . $this->db->escape(md5($data['password'])) 
			. "' WHERE user_id = '" . (int)$user_id . "'");
		}
	}
	
	public function deleteUser($user_id) {
		$this->db->query("DELETE FROM `" . DB_PREFIX . "user` WHERE user_id = '" . (int)$user_id . "'");
	}
	
	public function getTotalUsers($data = array()) {
		$sql = "SELECT COUNT(*) AS total FROM user";

		$query = $this->db->query($sql);

		return $query->row['total'];
	}

	public function getUser($user_id) {
		$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "user` WHERE user_id = '" . (int)$user_id . "'");
	
		return $query->row;
	}
	
	public function getUsers($data = array()) {
		if ($data) {
			$sql = "SELECT * FROM user ";

			$sort_data = array(
			'username',
			'status',
			'date_added'
			);
				
			if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
				$sql .= " ORDER BY " . $data['sort'];
			} else {
				$sql .= " ORDER BY username";
			}
				
			if (isset($data['order']) && ($data['order'] == 'DESC')) {
				$sql .= " DESC";
			} else {
				$sql .= " ASC";
			}

			if (isset($data['start']) || isset($data['limit'])) {
				if ($data['start'] < 0) {
					$data['start'] = 0;
				}

				if ($data['limit'] < 1) {
					$data['limit'] = 20;
				}
					
				$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
			}
				
			$query = $this->db->query($sql);

			return $query->rows;
		} else {
			$user_data = $this->cache->get('user.' . $this->config->get('config_language_id'));

			if (!$user_data) {
				$query = $this->db->query("SELECT * FROM user ");

				$user_data = $query->rows;
					
				$this->cache->set('user.' . $this->config->get('config_language_id'), $user_data);
			}

			return $user_data;
		}
	}
}
?>